__author__ = 'jian.yao'

from datetime import datetime
import time
import zlib
import struct

def timestamp(_datetime = None, _type = "string"):
    if(not _datetime) or (not isinstance(_datetime, datetime)):
        _timestamp = time.time()
    else:
        _timestamp = time.mktime(_datetime.timetuple()) + _datetime.microsecond / 1000000.0

    if("string" == _type.lower()):
        _timestamp = str(_timestamp)
    elif ("long" == type.lower()) or ("int" == type.lower()):
        _timestamp = long(_timestamp)

    return _timestamp

def data_compress(_buffer, _level = 6, _mixup = False):
    if(_buffer is None) or (_buffer == ""):
        return 0, ""
    _c = zlib.compress(_buffer, _level)
    _l = len(_c)
    if _mixup and _l >= 100:
        _h = 11
        _t = -51
        _converted = _c[:_h]+_c[_t]+_c[_h+1:_t]+_c[_h]+_c[_t+1:]
    else:
        _converted = _c
    return len(_buffer), _converted

def long_to_bytes(n, blocksize = 0):
    """long_to_bytes(n:long, blocksize:int) : string
    Convert a long integer to a byte string.

    If optional blocksize is given and greater than zero, pad the front of the
    byte string with binary zeros so that the length is a multiple of
    blocksize.
    """
    # after much testing, this algorithm was deemed to be the fastest
    s = ''
    n = long(n)
    pack = struct.pack
    while n > 0:
        s = pack('>I', n & 0xffffffffL) + s
        n = n >> 32
        # strip off leading zeros
    for i in range(len(s)):
        if s[i] != '\000':
            break
    else:
        # only happens when n == 0
        s = '\000'
        i = 0
    s = s[i:]
    # add back some pad bytes.  this could be done more efficiently w.r.t. the
    # de-padding being done above, but sigh...
    if blocksize > 0 and len(s) % blocksize:
        s = (blocksize - len(s) % blocksize) * '\000' + s
    return s

def get_sequence_item(_seq, _key, _value):
    return next((item for item in _seq if isinstance(item, dict) and item[_key] == _value), None)